var map = null;
var zoomLevel = 14;
var geocoder = null;

var icon = new GIcon();
icon.image = "./images/icon.png";
icon.iconAnchor = new GPoint(0, 0);
icon.infoWindowAnchor = new GPoint(0, 0);
icon.iconSize = new GSize(50, 50);

function load() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(33.58720308945914, 130.41204929351807), zoomLevel);
        geocoder = new GClientGeocoder();
        map.addControl(new GMapTypeControl()); 
        map.addControl(new GSmallMapControl());
        map.addControl(new GScaleControl());
        map.addControl(new GOverviewMapControl());
        GEvent.addListener(map, 'moveend', function() {
            if (zoomLevel != map.getZoom()) {
                map.clearOverlays();
                zoomLevel = map.getZoom();
            }
            getMarkers();
        });
        if (navigator.userAgent.match("MSIE")) {
            document.getElementById( "map" ).attachEvent("onmousewheel", mouseWheelZooming );
        }
        if (navigator.userAgent.match( "Gecko" )) {
            document.getElementById( "map" ).addEventListener("DOMMouseScroll", mouseWheelZooming, false);
        }
        if (navigator.userAgent.match("Safari")) {
            document.getElementById( "map" ).onmousewheel = mouseWheelZooming;
        }
    }
}

function getMarkers() {
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var sWLat = southWest.lat();
    var sWLng = southWest.lng();
    var nELat = northEast.lat();
    var nELng = northEast.lng();
    var zoom = map.getZoom();

    var url = "./getMarkers?"
            + "input[sWLat]=" + sWLat
            + "&input[sWLng]=" + sWLng
            + "&input[nELat]=" + nELat
            + "&input[nELng]=" + nELng
            + "&input[zoom]=" + zoom
            + "&input[order]=undefined"
            + "&input[lang]=jp"
            + "&input[viewon]=true"
            + "&input[viewoff]=true"
            + "&input[viewus]=true"
            + "&input[viewret]=true"
            + "&input[max]=200";

    GDownloadUrl(url, function(json, status) {
        if(status == 200){
          parseJson(json);
        }
    });
}

function parseJson(json) {
    var data = eval("("+json+")");
    var nameListText = '<ul>';
    for (var i=0; i < data.length; i++) {
        // node_off以外を表示
        if (data[i].type != 'node_off' && data[i].custom.TWITTER_DRINKING != undefined) {
            var id = data[i].id;
            var lat = data[i].lat;
            var lng = data[i].lng;
            var point = new GPoint(lng, lat);
            var marker = new GMarker(point, icon);
            map.addOverlay(marker);
            nameListText = nameListText + createNameListHTML(data[i].custom);
            var infoHtml = createInfoHtml(data[i]);
            GEvent.addListener(map, 'click', function(overlay, point) {
                try{
                    if (overlay) {
                      overlay.openInfoWindowHtml(infoHtml);
                    }
                }catch(e){}
            });
        }
    }
    nameListText = nameListText + '</ul>';
    
    // 飲み会リストの名前差し替え
    document.getElementById( "listname" ).innerHTML = nameListText;
}
    
function createInfoHtml(data) {
    return '<table>' +
//            '<tr><th>Id</th><td>' + data.id + '</td></tr>' +
            '<tr><th>Name</th><td>' + data.custom.TWITTER_DRINKING + '</td></tr>' +
//            '<tr><th>Parent Id</th><td>' + data.parentId + '</td></tr>' +
//            '<tr><th>User Id</th><td>' + data.userId + '</td></tr>' +
//            '<tr><th>Router Id</th><td>' + data.routerId + '</td></tr>' +
            '<tr><th>Address</th><td>' + data.address + '</td></tr>' +
            '</table>';
}

function mouseWheelZooming( event ){
    if (navigator.userAgent.match("MSIE")) { //IE
        var delta = event.wheelDelta;
        event.returnValue = false;
    }
    if (navigator.userAgent.match("Gecko")) { //Gecko
        var delta = event.detail * -1;
        event.preventDefault();
    }
    if (navigator.userAgent.match( "Safari")) { //Safari
        var delta = event.wheelDelta;
        event.returnValue = false;
    }
    map.setZoom(map.getZoom() + (delta < 0 ? 1 : -1 ));
}

function showAddress(address) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, zoomLevel);
        }
      }
    );
  }
}

function createNameListHTML(custom){
    
    // TWITTERのID設定
    var id = "";
    if(custom.TWITTER_DRINKING_TWITTER != undefined){
        id = custom.TWITTER_DRINKING_TWITTER;
    }

    // USTREAMのID設定
    id = id + ",";
    if(custom.TWITTER_DRINKING_USTREAM != undefined){
        id = id + custom.TWITTER_DRINKING_USTREAM;
    }
    
    return "<li><span onclick=showTwitterUstream('" + id + "')>" + custom.TWITTER_DRINKING + "</span></li>";
}

// TWITTER情報及びUSTREAMの表示。
function showTwitterUstream(id){
    var ids = id.split(",");
    var twitterId = ids[0];
    var ustreamId = ids[1];
    
    getTwitterData(twitterId);
    getUstreamData(ustreamId);
}

// TWITTERの情報取得。
function getTwitterData(twitterId){

    document.getElementById( "twitter_text" ).innerHTML = "now loading...";
    
    var url = "./getTwitter?"
            + "input[twitterId]=" + twitterId;

    GDownloadUrl(url, function(json, status) {
      document.getElementById( "twitter_text" ).innerHTML = parseTwitterJson(twitterId, json);
    });
    
    return false;
}

// TWITTERメッセージのJSONを解釈してHTMLに変換。
function parseTwitterJson(twitterId, json){
    var data = eval("("+json+")");
    
    if(data.length == 0){
        return "sorry, no comments are avalable.";
    }
    
    var text = "<ul>";
    
    for (var i=0; i < data.length; i++) {
        
        text = text + "<li><font color='#0000FF'><b>" + twitterId + "</b></font>&nbsp;&nbsp;&nbsp;" + data[i].text + "<font size='-3'>(" + data[i].created_at +  ")</font></li>";
    }
    
    return text + "</ul>";
}

function getUstreamData(ustreamId) {
   document.getElementById( "ustream_area" ).innerHTML = "now loading...";
   GDownloadUrl('./getUstreamJson?input[channel]=' + ustreamId , function(json, status) {
        if(status == 200){
            var data = eval("("+json+")");
            var tag = new String(data.ustream_tag);
            document.getElementById( "ustream_area" ).innerHTML = '<div align="center">' + tag.substring(0, tag.length - 2) + 'width="300" height="250" \></div>';
        }
    });

}